package com.bjsxt.config.exception;

import com.bjsxt.vo.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:liao
 * @Description:TODO
 * @date:2020/11/20
 */
@RestControllerAdvice //标识当前类为全局自定义异常类
public class GlobalExceptionHandler {
    /**
     * 当出现MethodArgumentNotValidException这个异常时 会调用下面的方法
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult jsonErrorHandler(MethodArgumentNotValidException e){
        return getAjaxResult(e.getBindingResult());
    }

    @ExceptionHandler(value = BindException.class)
    public AjaxResult jsonErrorHandlerForParams(BindException e){
        return getAjaxResult(e.getBindingResult());
    }

    /**
     * 此处封装了一个可以格式化异常信息的方法
     * @param
     * @return
     */
    private AjaxResult getAjaxResult(BindingResult bindingResult) {
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        //封装返回对象
        List<Map<String,Object>> list = new ArrayList<>();

        for (ObjectError allError : allErrors) {
            Map<String,Object> map = new HashMap<>();
            map.put("defaultMessage",allError.getDefaultMessage());
            map.put("objectName",allError.getObjectName());
            FieldError fieldError = (FieldError) allError;
            map.put("field",fieldError.getField());
            list.add(map);
        }

        return AjaxResult.fail("后端数据校验异常",list);
    }

}
